$(function () {
    $.get("../customsettlement/getTree", function(r){
        // dataTree = r;
        ztree = $.fn.zTree.init($("#menuTree"), setting, r.list);
        //展开所有节点
        ztree.expandAll(true);

        /*if(roleId != null){
         vm.getRole(roleId);
         }*/
    });
   // alert($("#file").val());
    $("#jqGrid").jqGrid({
        url: '../empbaseinfo/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden:true },
			{ label: '姓名', name: 'name', index: 'name' },
            { label: '身份证号', name: 'idno', index: 'idno' },
            { label: '出生日期', name: 'birthday', index: 'birthday',formatter:"date", formatoptions: {newformat:'Y-m-d'} },
			{ label: '性别', name: 'sex', index: 'sex',formatter: getDictInfo },
            { label: '求职状态', name: 'freeFlag', index: 'free_flag',
                formatter:function(v){
                    if(v=="0"){
                        return "待求职";
                    }else if(v=="1"){
                        return "求职进行中";
                    }else{
                        return v;
                    }
                }},
            { label: '年龄', name: 'age', index: 'age' },
            { label: '民族', name: 'nation', index: 'nation', editable: true, formatter: getDictInfo },
            { label: '婚否', name: 'married', index: 'married',
                formatter:function(v){
                    if(v=="0"){
                        return "未婚";
                    }else if(v=="1"){
                        return "已婚";
                    }else if(v=="2"){
                        return "离异";
                    }else{
                        return v;
                    }
                } },
            { label: '学历', name: 'education', index: 'education',formatter: getDictInfo },
            { label: '联系电话', name: 'telphone', index: 'telphone' },
			{ label: '政治面貌', name: 'polstatus', index: 'polstatus', editable: true, formatter: getDictInfo },
            { label: '紧急联系人', name: 'emergencycontact', index: 'emergencyContact' },
            { label: '紧急联系电话', name: 'emergencycontacttel', index: 'emergencyContactTel' },
            { label: '求职单位', name: 'company', index: 'company' },
            { label: '求职岗位', name: 'job', index: 'job',formatter: getDictInfo },
            { label: '户籍地址', name: 'localaddress', index: 'localAddress' },
            { label: '现居地址', name: 'address', index: 'address' },
            { label: '招聘渠道', name: 'recruitchannel', index: 'recruitChannel',formatter: getDictInfo },
            { label: '毕业院校', name: 'school', index: 'school' },
            { label: '专业', name: 'perfession', index: 'perfession' },
            { label: '身份证签发机关', name: 'carddepartment', index: 'cardDepartment' },
            { label: '开始日期', name: 'startdate', index: 'startdate' },
            { label: '结束日期', name: 'enddate', index: 'enddate' },
            { label: '家庭成员', name: 'familyinfo', index: 'familyinfo' },
            { label: '简历情况', name: 'jlqk', index: 'jlqk' },
            { label: '工作档案', name: 'jobfiles', index: 'jobfiles' },
            { label: '特殊人员', name: 'specialperson', index: 'specialperson' },

            { label: '内部编号', name: 'innerid', index: 'innerid' },  //(只有招聘部使用)
			{ label: '是否上岗', name: 'iswork', index: 'iswork' ,
                formatter:function(v){
                    if(v=="0"){
                        return "未上岗";
                    }else if(v=="1"){
                        return "已上岗";
                    }else if(v=="2"){
                        return "已离职";
                    }else{
                        return ""
                    }
                } },//(在外面公司是否已经就职)
            { label: '创建人', name: 'createperson', index: 'createperson' },
            { label: '创建时间', name: 'createtime', index: 'createtime' },
            { label: '资料流向', name: 'personfileto', index: 'personfileto'},

			{ label: '黑名单', name: 'status', index: 'status', hidden:true }, 		//是否进入黑名单(0,没进黑名单；1，进入黑名单)
			{ label: '删除标记', name: 'delFlag', index: 'del_flag', hidden:true },
            { label: '银行账号', name: 'bankaccount', index: 'bankAccount', hidden:true  },
            { label: '副银行账号', name: 'secbankaccount', index: 'secBankAccount', hidden:true  },
            { label: '身高', name: 'height', index: 'height', hidden:true  },
            { label: '体重', name: 'weight', index: 'weight', hidden:true  }
        ],
		viewrecords: true,
        height: $(window).height()*0.8,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
		//字段太多自动加载横轴滚动条
        shrinkToFit:false,
        autoScroll: false,
        gridComplete:function(){
		 	//doResize();
		 	//显示grid底部滚动条
            //$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "scroll" });
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    var r = utils.getDictList("post,dalx");
    vm.dictList1 = r.post;
    vm.dictList2 = r.dalx;

});


var vm = new Vue({
	el:'#rrapp',
	data:{
        q: {
            name: null,
            sex:null,
            education:null,
            minAge:null,
            maxAge:null,
            cardNo:null,
            job:null,
            company:null,
            sperson:null,
            recruitchannel:null

        },
		showList: true,
        showtable:false,

		title: null,
        jobfileslist:{},
        dictList1:{},
        dictList2:{},
        specialpersonlist:{},
        nationlist:{},polstatuslist:{},educationlist:{},recruitChannellist:{},
		empBaseinfo: {
            fileId:0,
            sex:0,
			status:0,
			married:0,
            iswork:0,
            jobfiles:[],
            specialperson:[],
			earchives:[{
                filetype: '',
                filename: ''
            }],
            certificates:[{
            	papername:'',
				paperno:'',
                startdate:'',
				confirmdate:'',
				validdate:''
                //id:1
			}],
            birthday:'',
            startdate:'',
            enddate:''
		},
        certificate:{
            startdate:'',
            enddate:'',
            validdate:''
        },
        //idCardPath: '',
        imageUrl: ''
	},
	methods: {
        addEarchiveItem: function(){
            this.empBaseinfo.earchives.push({
                filetype: '',
                filename: ''
            });
		},
        delEarchiveItem: function(index){
            this.empBaseinfo.earchives.splice(index,1);
        },
		addCertificateItem: function(){
        	this.empBaseinfo.certificates.push({
                papername:'',
                paperno:'',
                startdate:'',
                confirmdate:'',
                validdate:'',
                //id:this.id++
			});
		},
        delCertificateItem: function(index){
			this.empBaseinfo.certificates.splice(index,1);
		},
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.showtable=false;
			vm.title = "新增";
			vm.jobfileslist = {};
			vm.specialpersonlist = {};
            vm.nationlist = {};
            vm.polstatuslist = {};
            vm.educationlist = {};
            vm.recruitChannellist = {};
			vm.empBaseinfo = {
                company:"",
                idCardPathf:'',
                sex:0,
                status:0,
                married:0,
				iswork:0,
				jobfiles:[],
				specialperson:[],
				earchives:[{
					filetype: '',
					filename: ''
            	}],
                certificates:[{
                    papername:'',
                    paperno:'',
                    startdate:'',
                    confirmdate:'',
                    validdate:''
                }],
                birthday:'',
                startdate:'',
                enddate:''
			};

			this.getListinfo();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.showtable=false;

            vm.title = "修改";

            this.getListinfo();
            this.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.empBaseinfo.id == null ? "../empbaseinfo/save" : "../empbaseinfo/update";
			$.ajax({
				type: "POST",
			    url: url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.empBaseinfo),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../empbaseinfo/delete",
				    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get("../empbaseinfo/info/"+id, function(r){
                vm.empBaseinfo = r.empBaseinfo;
                var prevDiv = document.getElementById('preview');
                prevDiv.innerHTML = '<img src="' + r.imaurl + '" style="width: 330px;height: 170px;"/>';
            });
		},
		reload: function (event) {
			vm.showList = true;
            vm.showtable=false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.name,
                           'sex': vm.q.sex,
                     'education': vm.q.education,
                     'minAge':vm.q.minAge,
                     'maxAge':vm.q.maxAge,
                     'cardNo':vm.q.cardNo,
                     'company':vm.q.company,
                     'sperson':vm.q.sperson,
                     'recruitchannel':vm.q.recruitchannel,
                     'startTime':vm.q.startTime,
                     'endTime':vm.q.endTime},
                    page:page
            }).trigger("reloadGrid");
		},
		getListinfo: function(){
            $.get("../empbaseinfo/getListinfo", function(r){
                vm.jobfileslist = r.jobfiles;
                vm.specialpersonlist = r.sperson;
                vm.nationlist = r.nation;
                vm.polstatuslist = r.polstatus;
                vm.educationlist = r.education;
                vm.recruitChannellist = r.recruitChannel;
            });
		},
        showg:function(id){
            laydate.skin('molv');//切换皮肤，请查看skins下面皮肤库
            laydate({elem: '#'+id});//绑定元素
        },
        updatestatus: function (event) {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var params={"reason":vm.empBaseinfo.reason,
            "ids":ids
             }

            confirm('确定要锁定选中的员工？', function(){
                $.ajax({
                    type: "POST",
                    url: "../empbaseinfo/updatestatus",
                    contentType: "application/json",
                    data: JSON.stringify(params),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        normaldispatch:function(){
            dispatchType="dispatch_type01";
            vm.adddispatch();
        },
        tempdispatch:function(){
            dispatchType="dispatch_type02";
            vm.adddispatch();
        },
        adddispatch: function(event){
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var rowDatas = new Array();
            ids.forEach(function(val,index){
                rowDatas[index] = $("#jqGrid").jqGrid("getRowData",val);
            });
            for(var i=0;i<rowDatas.length;i++){
                if (rowDatas[i].freeFlag != '待求职') {
                    alert(rowDatas[i].name+'已经在求职中!');
                    return;
                }
            }
            openDialogTreeView('选择部门',$("#windowtree"),'400px','550px',1,ids);
        },
        addrecruitdamand: function(event){
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var rowDatas = new Array();
            ids.forEach(function(val,index){
                rowDatas[index] = $("#jqGrid").jqGrid("getRowData",val);
            });
             // alert(rowDatas[1].freeFlag);
            for(var i=0;i<rowDatas.length;i++){
                if (rowDatas[i].freeFlag != '待求职') {
                    alert(rowDatas[i].name+'已经在求职中!');
                    return;
                }
            }

            utils.openDialogView('需求管理', '../recruit/recruitdamandwin.html?ids='+ids,'900px', '500px',2);
            vm.reload();

        },

        handleAvatarSuccess: function(res, file) {
            vm.empBaseinfo.idCardPath = res.url;//URL.createObjectURL(file.raw);
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload: function(file) {

            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        lockInit: function (event) {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var rowDatas = new Array();
            ids.forEach(function(val,index){
                rowDatas[index] = $("#jqGrid").jqGrid("getRowData",val);
            });
            for(var i=0;i<rowDatas.length;i++){
                if (rowDatas[i].freeFlag != '0') {
                    alert(rowDatas[i].name+'已经在求职中!');
                    return;
                }
            }
            vm.showList = false;
            vm.showtable = true;

            vm.title = "解锁";

            // vm.getInfo(id);

        },

        unlock: function (event) {

            var url =  "../empblacklist/unlock" ;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.empBlacklist),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },

        popSettlement: function(dtlindex){
            popPage.popSettlement();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择求职单位",
                area: ['750px', '500px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popSettlement"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popSettlementGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var rowData=grid.jqGrid("getRowData",rowKey);
                    vm.empBaseinfo.company=rowData.settlementName;
                    vm.empBaseinfo.companyId=rowData.id;
                    // vm.actAssigndtlList[dtlindex].username=rowData.id;

                    layer.close(index);
                }
            });
        },
        btnImoprt: function(){
            utils.openDialogExcelView("../empbaseinfo/list/export?op=download","../empbaseinfo/import");
        }

    }
});
var unitId="";
var dispatchType="";
//打开一颗树
openDialogTreeView=function(title,url,width,height,type,ids){
    if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端，就使用自适应大小弹窗
        width='auto';
        height='auto';
    }else{//如果是PC端，根据用户设置的width和height显示。

    }
    layer.open({
        type: type,
        offset: '50px',
        skin: 'layui-layer-molv',
        title: title,
        area: [width, height],
        maxmin: true, //开启最大化最小化按钮
        content: url,
        btn: ['确定','关闭'],
        btn1:function(index, layero){
            if(unitId==""){
                alert("请选择派遣单位！");
                return;
            }
            var params = {
                dispatchType:dispatchType,
                unitId:unitId,
                ids:ids.join(",")
            }
            $.ajax({
                type: "POST",
                url: "../empbaseinfo/insertdispatch",
                contentType: "application/json",
                data: JSON.stringify(params),
                dataType:"json",
                async:false,
                cache:false,
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            layer.close(index);
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
        btn2:function(index){
            layer.close(index);
        }
    });
}
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "unitId",
            pIdKey: "unitCode",
            rootPId: null
        },
        key: {
            url:"nourl"
        }
    },
    check:{
        enable:false,//是否显示勾选框
        nocheckInherit:true
    },
    callback:{
        // beforeClick: getCurrentNode
        onClick : zTreeOnClick
    }
};
function zTreeOnClick(e, treeId, node){
    unitId=node.unitId;
};